import storage from "./storage";
import md5 from "md5";
import request from "./request";
import {deepCopy} from "../utils";

/** 队列 */

function queue_shutdown() {
    clearInterval(queue_loop.t);
    clearInterval(queue_loop.t1);
    queue_loop.t = null;
    queue_loop.t1 = null;
}

function find_type(type) {
    let logType = storage.config_info.logType || [];
    return logType.join().indexOf(type) !== -1;
}

function queue_loop() {

    //如果采集度为0，则停止启动
    if(storage.config_info.degree === 0) return console.warn('[logjs] When the acquisition degree is zero, the probe will stop working. ');

    //消息发送器
    queue_loop.t = setInterval(function () {
        request.fetch();
    }, 1000);

    //消息收集器
    queue_loop.t1 = setInterval(function () {

        //采样率筛选
        if(!degree_control()) return false;

        let errorSize = storage.error_info.length;
        let clickSize = storage.click_info.length;
        let ioSize = storage.io_info.length;
        let diySize = storage.diy_info.length;

        let param = {};

        if (find_type("error") && errorSize) param.error_list = deepCopy(storage.error_info);
        if (find_type("click") && clickSize) param.click_list = deepCopy(storage.click_info);
        if (find_type("io") && ioSize) param.io_list = deepCopy(storage.io_info);
        if (find_type("diy") && diySize) param.diy_list = deepCopy(storage.diy_info);

        ((find_type("error") && errorSize) || (find_type("click") && clickSize) || (find_type("io") && ioSize) || (find_type("diy") && diySize)) && queue.push(param);
    }, 800);
}

function queue_push(info) {
    //是否携带 端 信息 - 默认携带
    info.terminal_info = storage.terminal_info;
    //携带性能信息
    info.performance_info = storage.performance_info;

    info.uid = md5(storage.terminal_info.cip + navigator.userAgent);

    //将终端标识塞入报文中
    storage.config_info.id && (info.id = storage.config_info.id);

    //信息进入队列后，将存储模块信息清理
    storage.click_info = [];
    storage.error_info = [];
    storage.io_info = [];
    storage.diy_info = [];

    queue.queue.push(info);
}

//采样率决定器
function degree_control(){
    let tempDegree = storage.config_info.degree * 100;
    let random = ~~(Math.random() * 100);
    return random < tempDegree;
}

let queue = {
    queue: [], //待执行队列
    push: queue_push, //队列推入方法
    shutdown: queue_shutdown, //停止队列执行
    loop: queue_loop, //队列执行器
};

export default queue;